package com.kma.ncpractice2013.auth;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 *
 * @author Viktor
 */
public class AuthorizationServlet extends HttpServlet
{

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws javax.servlet.ServletException if a servlet-specific error occurs
     * @throws java.io.IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, NamingException
    {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String uname = request.getParameter("username");
        String pass = request.getParameter("password");




        try
        {
            int access_level = getAccessLevel(uname, pass, out);

            if(access_level < 5) //it's magic(<5 means confirmed or higher), do something later
            {
                String url = request.getContextPath()+ "/accept.jsp";
                String str = response.encodeRedirectURL(url);
                HttpSession sess = request.getSession();
                sess.setAttribute("username", uname);
                sess.setAttribute("auth", "true");
                sess.setAttribute("access_level", String.valueOf(access_level));
                out.print(access_level);
                response.sendRedirect(str);
            }
            else
            {

                String url = request.getContextPath()+"/deny.jsp";
                String s = response.encodeRedirectURL(url);
                response.sendRedirect(s);
            }
        }
        catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }


    }
    private int getAccessLevel(String uname, String pass, PrintWriter o) throws SQLException, NamingException                  //returns 100 if username not exist, access level else
    {

        Context ctx=new InitialContext();
        DataSource ds=(DataSource)ctx.lookup("jdbc/security");
        Connection conn =ds.getConnection();
        try
        {
            PreparedStatement ps = conn.prepareStatement("select SALT from USERS where LOGIN = ?");
            ps.setString(1, uname);
            ResultSet execute = ps.executeQuery();
            if(execute.next())
            {
                String salt = execute.getString("SALT");

                ps = conn.prepareStatement("select GROUP_ID from USERS where LOGIN = ? and PASSWORD = ?");
                ps.setString(1, uname);
                ps.setString(2, Crypto.getHash(salt, pass, "SHA-256"));

                execute = ps.executeQuery();

                if(execute.next())
                {
                    return execute.getInt("GROUP_ID");
                }
            }



        }
        catch (Exception e)
        {

            o.print(e.getMessage());

        }
        finally
        {
            conn.close();
        }


        return 100;

    }


    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws javax.servlet.ServletException if a servlet-specific error occurs
     * @throws java.io.IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        //processRequest(request, response);

    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws javax.servlet.ServletException if a servlet-specific error occurs
     * @throws java.io.IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        try
        {
            processRequest(request, response);
        }
        catch (NamingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }
}
